module.exports = function(app) {
  return new MessageRemote(app);
};

let rsmq = global.rsmq,
  db = global.db;

let col = db.collection('tim_messages');

rsmq.on('msg', function(msg) {
  console.log('iddddd', msg);
  console.log(rsmq.workingType);
  if (rsmq.workingType !== rsmq.MSG_QUIT) {
    rsmq.workingType = rsmq.MSG_QUIT;
    rsmq.emit('msg-quit', { qname: 'msg' });
  };
});

rsmq.on('msg-quit', function(obj) {
  rsmq.getQueueAttributes(obj.qname).then(queue => {
    console.log('queue===========', queue);
    if (queue.msgs > 0) {
      rsmq.receiveMessage({ qname: obj.qname }).then(msg => {
        console.log('received=========', msg);
        rsmq.deleteMessage({ qname: obj.qname, id: msg.id }).then(r => {
          console.log('deleted===========', r);
          rsmq.emit('msg-quit', obj);
        }).catch(e => rsmq.emit('error', e));
      }).catch(e => rsmq.emit('error', e));
    } else {
      rsmq.workingType = rsmq.NORMAL;
    }
  }).catch(e => rsmq.emit('error', e));
});



var MessageRemote = function(app) {
  this.app = app;
  this.rsmq = rsmq;
  this.channelService = app.get('channelService');
};

var prototype = MessageRemote.prototype;


prototype.saveRecord = function(opts, cb) {
  let self = this;


  // 进队
  this.rsmq.sendMessage({ qname: 'msg', message: 'heiheihei' }).then(r => {
    console.log('send------------', r);
    // return Promise.resolve('sent');
    // }).then(r => {
    //   return new Promise((resolve, reject) => {
    //     // 站队
    //     self.rsmq.receiveMessage({ qname: 'msg' }).then(result => {
    //       console.log('result=======', result);
    //       resolve(result);
    //     }).catch(reject);
    //   });
    // }).then(r => {
    //   // 出队
    //   return self.rsmq.deleteMessage({ qname: 'msg', id: r.id }).then(del => {
    //     console.log('delete===========', del);
    //   });
  }).catch(e => console.error(e));

  // 站队
  // this.rsmq.receiveMessage({ qname: 'msg' }).then(result => {
  //   console.log('result=======', result);

  //   self.rsmq.deleteMessage({ qname: 'msg', id: result.id }).then(del => {
  //     console.log('delete===========', del);
  //   }).catch(e => { console.error(e); });
  // }).catch(e => console.error(e));




  console.log('thisopts', opts);

  cb();
};
